module.exports = (app) => {
    const router = app.router;

    const Batch = app.models.Batch;

    const Good = app.models.Good;

    router.get('/batches', function* () {
        const query = this.query;

        const batches = yield Batch.query(qb => {
            qb.where('deleted', Batch.NOT_DELETED);

            if(query.good_id !== 'all' && +query.good_id > 0) {
                qb.where('good_id', query.good_id);
            }
        })
        .fetchItems({
            page_size: query.page_size,
            page_num: query.page_num
        }, {
            withRelated: ['creator', 'good']
        });

        this.body = batches;
    });

    router.post('/batches', function * () {
        const body = this.request.body;
        body.creator = this.get('x-user');

        const batch = Batch.safeForge(body);

        yield batch.save();

        const good = yield Good.where({
            id: body.good_id
        })
        .fetch();

        good.safeSet({
            stock: good.get('stock') + body.stock
        });

        yield good.save();

        this.body = body;
    });

    router.put('/batches/:id', function * () {
        const body = this.request.body;

        const batch = yield Batch.where({
            id: this.params.id
        })
        .fetch();

        const good = yield Good.where({
            id: body.good_id
        })
        .fetch();

        delete body.creator;
        delete body.good;

        batch.safeSet(body);

        good.safeSet({
            stock: good.get('stock') + body.stock
        });

        yield batch.save();

        yield good.save();

        this.body = body;
    });

    router.delete('/batches/:id', function *() {
        let batch = yield Batch.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        batch.set('deleted', Batch.DELETED);

        yield batch.save();

        const good = yield Good.where({
            id: batch.get('good_id')
        })
        .fetch();
        if(good.get('stock') > batch.get('stock')) {
            good.safeSet({
                stock: good.get('stock') - batch.get('stock')
            });
            yield good.save();
        }

        this.body = this.params;
    });
};
